package com.sq.partner.manager.controller;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayVatRate;
import com.sq.partner.manager.mybatis.model.VatFromDto;
import com.sq.partner.manager.service.IGatewayClearCacheManager;
import com.sq.partner.manager.service.IGatewayVatService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 *  增值税率管理
 * @author dinghao
 *
 */
@Controller
@RequestMapping(value = "/systemManager")
public class GatewayVatController{

	private static Logger logger = LogUtil.getLog(GatewayVatController.class);

	@Resource
	private IGatewayVatService vatService;
	@Resource
	IGatewayClearCacheManager gatewayClearCacheManager;	

	@RequestMapping(value="/vatManager")
	public String rateManager(Model model) throws Exception{
		return "systemManager/vatManager";
	}

	@RequestMapping(value="/vatManager/initAllVats")
	public @ResponseBody Page initAllVats(Integer pageIndex,GatewayVatRate vat) throws Exception
	{
		Page page=new Page();
		Map<String, Object> param = new HashMap<String, Object>();
		
		if(pageIndex != -1){
			page.setCurrent(pageIndex);
			param =SqlUtil.buildPageMap(page);
		}
		if(StrUtil.isNotEmpty(vat.getCoreRiskCode())){
			param.put("coreRiskCode", vat.getCoreRiskCode());
		}
		page.setType(param);
		Page p = vatService.queryPage(page);
		return p;
	}
	@RequestMapping(value="/vatManager/vatSync")
	public @ResponseBody Result vateSync(HttpServletRequest req) throws Exception  { 
		logger.info(" 本机地址："+InetAddress.getLocalHost().getHostAddress());
		/*Map <String ,VatFromDto>  map= vatService.queryFromVat();
		int successVat=0,failVat=0;
		if(map.size()>0){
			for (Map.Entry<String, VatFromDto> entry : map.entrySet()) {
				try {
					GatewayVatRate vatRate = vatService.queryToVat(entry.getValue());
					if(vatRate!=null){
						if(!(vatRate.getVatRate().equals(entry.getValue().getVatRate()))){
							boolean up=vatService.updateVat(entry.getValue());
							if(up){
								successVat++;
							}
							else {
								failVat++;
							}
						}
					}else{
						boolean add=vatService.addVat(entry.getValue());
						if(add){
							successVat++;
						}
						else {
							failVat++;
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					failVat++;
					logger.error("同步失败，失败模板条款代码："+entry.getValue().getCoreRiskCode()+",机构代码:"+entry.getValue().getDeptCode());
				}

			}
			gatewayClearCacheManager.clearAllCache();
		}
		
		if(failVat>0){
			return Result.success("增值税率同步完成，成功"+successVat+"条,失败："+failVat+"条");
		}else{
			return Result.success("增值税率同步完成，成功"+successVat+"条");
		}
	    */
		
		boolean flagBase=false;
		List<Object[]> lists=null;
		try {
			lists=vatService.queryListObjectsFromVat();
			if(lists!=null&&lists.size()>0){
				flagBase=vatService.BatchInsertVatRate(lists);
			}
			if(flagBase){
				flagBase=vatService.DelOldVatAndCopyNewVatRate();
			}
		} catch (Exception e) {
			logger.error("从VMS同步税率失败，请检查！");
		}
		if(flagBase){
			return Result.success("从VMS全量同步税率成功,更新数据"+lists.size()+"条");
		}else{
			return Result.success("从VMS全量同步税率失败，请检查！");
		}
		
	}


	@RequestMapping(value="/vatManager/singleSyncVat")
	public @ResponseBody Result singleSyncVat(HttpServletRequest req,GatewayVatRate gatewayVatRate) throws Exception  {  
		
		if(gatewayVatRate!=null){
			try {
				VatFromDto varFromDto= vatService.querySingleVat(gatewayVatRate);
				if(varFromDto!=null){
					boolean up=vatService.updateVat(varFromDto);
					if(up){
						return Result.success("增值税率同步成功");
					}
					else {
						return Result.error("增值税率同步失败");
					}
				}else{
					return Result.error("vat库未查询到增值税信息");
				}
			} catch (Exception e) {
				logger.error("增值税率同步失败");
				return Result.error("增值税率同步失败");
			}
		
		}else{
			return Result.error("请求参数异常");
		}
	}

	
	@Scheduled(cron="0 0 2 * * ?")//cron="0 0 2 * * ?"
	public void vatSyncSchedule() throws Exception {
		String local = Inet4Address.getLocalHost().getHostAddress();
		logger.info(" 本机地址："+ local);
		List<DictDto> correctIpList = DictCache.getDict("vatSyncIp");
		if(null!=correctIpList && correctIpList.size() > 0){
			String correctIp = correctIpList.get(0).getCode();
			if(!local.equals(correctIp)){
				return ;
			}
		}
		/*Map <String ,VatFromDto>  map= vatService.queryFromVat();
		int successVat=0,failVat=0;
		if(map.size()>0){
			
			for (Map.Entry<String, VatFromDto> entry : map.entrySet()) {
				try {
					GatewayVatRate vatRate = vatService.queryToVat(entry.getValue());
					if(vatRate!=null){
						if(!(vatRate.getVatRate().equals(entry.getValue().getVatRate()))){
							boolean up=vatService.updateVat(entry.getValue());
							if(up){
								successVat++;
							}
							else {
								failVat++;
								logger.error("更新失败，失败模板条款代码："+entry.getValue().getCoreRiskCode()+",机构代码:"+entry.getValue().getDeptCode());
							}
							
						}
					}else{
						boolean add=vatService.addVat(entry.getValue());
						if(add){
							successVat++;
						}
						else {
							failVat++;
							logger.error("添加失败，失败模板条款代码："+entry.getValue().getCoreRiskCode()+",机构代码:"+entry.getValue().getDeptCode());
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.error("同步失败，失败模板条款代码："+entry.getValue().getCoreRiskCode()+",机构代码:"+entry.getValue().getDeptCode());
				}

			}*/
			
			boolean flagBase=false;
			List<Object[]> lists=null;
			try {
				lists=vatService.queryListObjectsFromVat();
				if(lists!=null&&lists.size()>0){
					flagBase=vatService.BatchInsertVatRate(lists);
				}
				if(flagBase){
					flagBase=vatService.DelOldVatAndCopyNewVatRate();
				}
			} catch (Exception e) {
				logger.error("从VMS同步税率失败，请检查！");
			}
			
			try {
				gatewayClearCacheManager.clearAllCache();
			} catch (Exception e) {
				logger.error("清除缓存失败"+e);
			}
			
			if(flagBase){
				logger.info("从VMS全量同步税率成功,更新数据"+lists.size()+"条");
			}else{
				logger.info("从VMS全量同步税率失败，请检查！");
			}
//			logger.info(" 增值税调度任务完成, "+"成功"+successVat+"条,失败："+failVat+"条");
//		}
	}
	
}
